package property

import (
	"bufio"
	"fmt"
	"game/readygo/util"
	"os"
	"reflect"
	"strings"

	"go.uber.org/zap"
)

type Property struct {
	entry map[string]string
}

func LoadFromFile(filePath string) (*Property, error) {
	file0, err := os.Open(filePath)
	if err != nil {
		fmt.Println("err1", err)
		return nil, err
	}
	defer file0.Close()

	var property Property
	property.entry = make(map[string]string)

	scanner := bufio.NewScanner(file0)
	for scanner.Scan() {
		line := scanner.Text()
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		keyv := strings.Split(line, "=")
		if len(keyv) < 2 {
			zap.L().Warn("property in line may define wrong", zap.String("line", line))
			continue
		}
		key := keyv[0]
		value := ""
		for i := 1; i < len(keyv); i++ {
			value += keyv[1]
		}
		property.entry[key] = value
	}
	return &property, nil
}

func Load(filePath string, obj interface{}) {
	zap.L().Info("Load property file in", zap.String("file", filePath))
	property, err := LoadFromFile(filePath)
	if err != nil {
		return
	}
	// fmt.Println(property)
	rType := reflect.TypeOf(obj).Elem()
	//反射出obj的字段映射
	tagNameMap := make(map[string]string)
	for i := 0; i < rType.NumField(); i++ {
		rField := rType.Field(i)
		tagName := rField.Tag.Get("name")
		tagNameMap[tagName] = rField.Name
	}
	//通过反射设置obj的字段值
	rValue := reflect.ValueOf(obj).Elem()
	for key, value := range property.entry {
		fieldName, exist := tagNameMap[key]
		if !exist {
			continue
		}
		rField := rValue.FieldByName(fieldName)
		util.ReflectSetRawValue(rField, value)
	}
	// fmt.Println(obj)
}
